package cn.wolfcode.wolf2world.schedule;

import cn.wolfcode.wolf2world.domain.Strategy;
import cn.wolfcode.wolf2world.domain.UserStrategyFavoer;
import cn.wolfcode.wolf2world.redis.service.StaticRedisService;
import cn.wolfcode.wolf2world.redis.service.UserRedisService;
import cn.wolfcode.wolf2world.service.UserStrategyFavoerService;
import cn.wolfcode.wolf2world.vo.StaticRedisVO;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020/8/18 0:19
 */
//@Component
@Slf4j
public class RedisDataPersistencaJob {

    @Autowired
    private StaticRedisService staticRedisService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserRedisService userRedisService;
    @Autowired
    private UserStrategyFavoerService userStrategyFavoerService;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void doWork() {
        log.info("redis攻略统计开始执行持久化");
        //获取所有攻略统计数据
       List<StaticRedisVO> list = staticRedisService.getRedisStrategy();
       //遍历集合，获取每一个vo
        for (StaticRedisVO vo : list) {
            Query query = Query.query(Criteria.where("_id").is(vo.getSid()));
            Update update = new Update();
            update.set("viewnum",vo.getViewnum());
            update.set("replynum",vo.getReplynum());
            update.set("favornum",vo.getFavornum());
            update.set("sharenum",vo.getSharenum());
            update.set("thumbsupnum",vo.getThumbsupnum());

            UpdateResult updateResult = mongoTemplate.updateMulti(query, update, Strategy.class);
        }
        log.info("redis攻略统计执行持久化完毕");
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void userStrategyFavor() {
        log.info("redis用户收藏攻略开始执行持久化");
        //在redis中匹配keys user_strategy_favor:*
        List<UserStrategyFavoer> list = userRedisService.getUserStrategyFaverList();
        //保存到mongodb数据库中
        for (UserStrategyFavoer favoer : list) {
            userStrategyFavoerService.update(favoer);
        }
        log.info("redis用户收藏攻略执行持久化完毕");
    }


}
